package cn.bytecollege.user.controller;

import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.User;
import cn.bytecollege.common.util.MD5Util;
import cn.bytecollege.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "UserLoginController",value = "/user/login")
public class UserLoginController extends HttpServlet {
    private UserService userService = null;
    public  UserLoginController(){
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        //获取数据库的username
        User user = userService.findUserByUsername(username);
        if (user == null){
            //用户名不存在
            msg="没有该用户";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
            return;
        }
        //判断用户名和密码是否相同
        if(MD5Util.md5Encode(password).equals(user.getUserPassword())&&username.equals(user.getUsername())){
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            request.getParameter("user");

            response.sendRedirect("/index");
        }else{
            msg="账户或者密码错误";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
        }
    }
}
